package com.xlhj.yucloud.controller;

import com.xlhj.yucloud.common.ResultData;
import com.xlhj.yucloud.entity.SysMenuInfo;
import com.xlhj.yucloud.service.SysMenuInfoService;
import com.xlhj.yucloud.web.model.MenuInfoReqDto;
import com.xlhj.yucloud.web.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: liucaijing
 * @description: SysMenuController
 * @date: 2021/9/28 20:27
 */
@RestController
@RequestMapping("/system/menu")
@RequiredArgsConstructor
public class SysMenuController {

    private final LoginService loginService;
    private final SysMenuInfoService menuInfoService;

    @GetMapping("/getMenuList")
    public ResultData getMenuList(MenuInfoReqDto reqDto) {
        List<SysMenuInfo> menuInfoList = menuInfoService.selectMenuInfoList(reqDto, loginService.getUserInfo().getId());
        return ResultData.success().data(menuInfoList);
    }

    @PostMapping("/addMenuInfo")
    public ResultData addMenuInfo(@RequestBody SysMenuInfo menuInfo) {
        Boolean menuNameUnique = menuInfoService.checkMenuNameUnique(menuInfo.getId(), menuInfo.getMenuName(), menuInfo.getParentId());
        if (menuNameUnique) {
            return ResultData.error().message("新增菜单" + menuInfo.getMenuName() + "失败,菜单名称已存在");
        }
        boolean save = menuInfoService.save(menuInfo);
        if (save) {
            return ResultData.success();
        } else {
            return ResultData.error();
        }
    }

    @PostMapping("/updateMenuInfo")
    public ResultData updateMenuInfo(@RequestBody SysMenuInfo menuInfo) {
        Boolean menuNameUnique = menuInfoService.checkMenuNameUnique(menuInfo.getId(), menuInfo.getMenuName(), menuInfo.getParentId());
        if (menuNameUnique) {
            return ResultData.error().message("修改菜单" + menuInfo.getMenuName() + "失败,菜单名称已存在");
        }
        if (menuInfo.getId().longValue() == menuInfo.getParentId()) {
            return ResultData.error().message("修改菜单" + menuInfo.getMenuName() + "失败,父级菜单不能选择自己");
        }
        boolean update = menuInfoService.updateById(menuInfo);
        if (update) {
            return ResultData.success();
        } else {
            return ResultData.error();
        }
    }
}
